package umaine.ece471.cookbook;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class NewsFeed extends Activity {
    /** Called when the activity is first created. */
	
	ArrayList<SingleNewsItem> newsList;
	ArrayAdapter<String> aa;
	ListView myListView;
	String urlAddress;
	String urlCaption;
	SingleNewsItem selectedNews;
	Context context;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_list);
        
        newsList=new ArrayList<SingleNewsItem>();
        urlAddress="http://www.agra-net.com/content/agra/rssfeeds/rss_20000041727.xml";
        urlCaption="Latest Food News";
        context=getApplication();
        
        myListView=(ListView) findViewById(R.id.listNewsView);
        
        myListView.setOnItemClickListener(new OnItemClickListener(){
        	public void onItemClick (AdapterView<?> _av, View _v, int _index, long _id){
        		selectedNews=newsList.get(_index);
        		showNiceDialogBox(selectedNews,context);
        	}
        });
        
        String currTime=android.text.format.DateFormat.format("yyy-MM-dd hh:mm:ss", new java.util.Date()).toString();
        this.setTitle("Cookbook - Food News RSS Feed "+currTime);
    }
    
    @Override
    protected void onResume()
    {
    	
    	
    	super.onResume();
    	try{
    		URL url =new URL(urlAddress);
    		URLConnection connection;
    		connection = url.openConnection();
    		HttpURLConnection httpConnection = (HttpURLConnection) connection;
    		int responseCode = httpConnection.getResponseCode();
    		if(responseCode == HttpURLConnection.HTTP_OK){
    			
    			InputStream in = httpConnection.getInputStream();
    			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    			DocumentBuilder builder = factory.newDocumentBuilder();
    			Document dom = builder.parse(in);
    			Element root = dom.getDocumentElement();
    			NodeList properties = root.getElementsByTagName("item");
    			if ((properties!=null)&&(properties.getLength()>0)){
    				for (int i=0; i<properties.getLength();i++){
    					dissectNode(properties,i);
    				}
    			}
    		}
    		ArrayAdapter<SingleNewsItem> aaNews = new ArrayAdapter<SingleNewsItem>(
					this, android.R.layout.simple_list_item_1, newsList);
			myListView.setAdapter(aaNews);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			Toast.makeText(context, "Trouble!!!", 1).show();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
	}// onResume
    
    public void dissectNode (NodeList properties, int i)
    {
    	try{
	    	Element entry = (Element) properties.item(i);
			Element title = (Element) entry.getElementsByTagName("title").item(0);
			Element description = (Element) entry.getElementsByTagName("description").item(0);
			Element pubDate = (Element) entry.getElementsByTagName("pubDate").item(0);
			Element link = (Element) entry.getElementsByTagName("link").item(0);
			String titleValue = title.getFirstChild().getNodeValue();
			String descriptionValue = description.getFirstChild().getNodeValue();
			String dateValue = pubDate.getFirstChild().getNodeValue();
			String linkValue = link.getFirstChild().getNodeValue();
			SingleNewsItem singleItem = new SingleNewsItem(dateValue,
					titleValue, descriptionValue, linkValue);
			newsList.add(singleItem);
    	}
    	catch (DOMException e)
    	{
    		e.printStackTrace();
    	}
	}// dissectNode

    public void showNiceDialogBox(SingleNewsItem selectedNewsItem,
			Context context) {
		// assemble a nice looking dialog box
		try {
			final Uri myLink = Uri.parse(selectedNewsItem.getLink());
			AlertDialog.Builder myBuilder = new AlertDialog.Builder(this);
			myBuilder
					.setIcon(R.drawable.chef_color)
					.setTitle(urlCaption)
					.setMessage(selectedNewsItem.getTitle() + "\n\n"
									+ selectedNewsItem.getDescription() + "\n")
					.setPositiveButton("Close", null)
					.setNegativeButton("More", new OnClickListener() {
						public void onClick(DialogInterface dialog, int whichOne) {
							// use native web browsing
							Intent webIntent = new Intent(Intent.ACTION_VIEW, myLink);
							startActivity(webIntent);
						}
					})// setNegativeButton
					.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}// showNiceDialogBox

}